const Parse = require('parse/node');
const {toJSON,toJSONList}=require('../helpers/parse');
const moment=require('moment');
const _=require('lodash');
const config = require('../config/config');
const ParseHelper = require('../helpers/parse');
const CheckInObj = Parse.Object.extend("v5_check_in"); 
const CheckInRecordObj = Parse.Object.extend("v5_check_in_record"); //排课表

//微信小程序签到部分
async function addCheckIn(username, checkInName, remarks, number) {
    const checkInObj = new CheckInObj();
    // 动态生成实验对象集合
    const experiments = [];
    for (let i = 1; i <= number; i++) {
        experiments.push({ name: `实验${i}`});
    }
    // 设置字段
    checkInObj.set("owner", username);
    checkInObj.set("checkInName", checkInName);
    checkInObj.set("remarks", remarks);
    checkInObj.set("experiments", experiments);
    await checkInObj.save(null, { useMasterKey: true });
    return ParseHelper.toJSON(checkInObj);
}


async function getCheckInList(username) {
    const query = new Parse.Query(CheckInObj); // 假设签到对象的类名是 CheckInObj
    query.equalTo("owner", username);
    try {
        const results = await query.find({ useMasterKey: true });
        return results.map(record => ParseHelper.toJSON(record));
    } catch (error) {
        console.error("Error retrieving check-in list:", error);
        throw error;
    }
}


async function getCheckInInfoById(id) {
    const query = new Parse.Query(CheckInObj); // 假设签到对象的类名是 CheckInObj
    query.equalTo("objectId", id);
    query.notEqualTo("isDeleted", true);
    
    try {
        // 使用 first() 获取单个对象
        const result = await query.first({ useMasterKey: true });
        if (!result) {
            return null; // 如果没有找到记录，返回 null
        }
        return ParseHelper.toJSON(result); // 转换为 JSON 格式
    } catch (error) {
        console.error("Error retrieving check-in info:", error);
        throw error;
    }
}


async function getCheckInRecord(id, userName) {
    const checkInRecordQuery = new Parse.Query(CheckInRecordObj); // 假设签到记录的类名是 CheckInRecordObj
    checkInRecordQuery.equalTo("checkInId", id);
    checkInRecordQuery.equalTo("userName", userName);
    checkInRecordQuery.notEqualTo("isDeleted", true);
    try {
        // 查找签到记录
        let record = await checkInRecordQuery.first({ useMasterKey: true });

        // 如果没有找到记录，新建一条
        if (!record) {
            // 查找 checkIn 对象
            const checkInQuery = new Parse.Query(CheckInObj); // 假设签到对象的类名是 CheckInObj
            checkInQuery.equalTo("objectId", id);
            checkInQuery.notEqualTo("isDeleted", true);
            const checkIn = await checkInQuery.first({ useMasterKey: true });
            if (!checkIn) {
                throw new Error("Check-in object not found.");
            }
            // 根据 checkIn 对象的 experiment 字段生成 progressSteps
            const experiments = checkIn.get("experiments") || [];
            const progressSteps = experiments.map((exp, index) => ({
                id: index + 1, // 唯一 ID，从 1 开始排列
                label: exp.name,
                steps: [
                    { step: "tutorials", label: "导课",ischeckIn:false },
                    { step: "answering", label: "答疑",ischeckIn:false },
                    { step: "acceptance", label: "验收",ischeckIn:false }
                ]
            }));
            
            // 创建新的签到记录
            const newRecord = new CheckInRecordObj();
            newRecord.set("checkInId", id);
            newRecord.set("userName", userName);
            newRecord.set("progressSteps", progressSteps);
            await newRecord.save(null, { useMasterKey: true });
            
            record = newRecord; // 设置为新创建的记录
        }

        return ParseHelper.toJSON(record); // 转换为 JSON 格式
    } catch (error) {
        console.error("Error retrieving or creating check-in record:", error);
        throw error;
    }
}

async function checkIn(recordId, experimentId, stepName) {
    console.log("recordId:", recordId);
    console.log("experimentId:", experimentId);
    console.log("stepName:", stepName);
    const checkInRecord = CheckInRecordObj.createWithoutData(recordId);
    try {
        // 加载完整数据
        await checkInRecord.fetch({ useMasterKey: true });

        // 获取当前的 progressSteps
        let progressSteps = checkInRecord.get("progressSteps");
        if (!Array.isArray(progressSteps)) {
            throw new Error("progressSteps 字段不存在或格式错误");
        }

        // 查找指定的 experimentId 的实验项目
        const progressStep = progressSteps.find(exp => exp.id === experimentId);
        if (!progressStep) {
            throw new Error("未找到指定的实验项目");
        }

        // 查找指定步骤
        const stepIndex = progressStep.steps.findIndex(s => s.step === stepName);
        if (stepIndex === -1) {
            throw new Error("未找到指定的签到步骤");
        }

        // 更新步骤状态
        progressStep.steps[stepIndex].ischeckIn = true;
        progressStep.steps[stepIndex].checkInTime = formatDateToStandard(new Date());

        // 更新 progressSteps 并保存
        checkInRecord.set("progressSteps", progressSteps);

        const result = await checkInRecord.save(null, { useMasterKey: true });
        console.log("签到成功，数据已更新");
        return ParseHelper.toJSON(result); // 返回更新后的数据
    } catch (error) {
        console.error("更新签到进度时发生错误:", error);
        throw error;
    }
}


async function cancelCheckIn(recordId, experimentId, stepName) {
    console.log("recordId:", recordId);
    console.log("experimentId:", experimentId);
    console.log("stepName:", stepName);
    const checkInRecord = CheckInRecordObj.createWithoutData(recordId);
    try {
        // 加载完整数据
        await checkInRecord.fetch({ useMasterKey: true });

        // 获取当前的 progressSteps
        let progressSteps = checkInRecord.get("progressSteps");
        if (!Array.isArray(progressSteps)) {
            throw new Error("progressSteps 字段不存在或格式错误");
        }

        // 查找指定的 experimentId 的实验项目
        const progressStep = progressSteps.find(exp => exp.id === experimentId);
        if (!progressStep) {
            throw new Error("未找到指定的实验项目");
        }

        // 查找指定步骤
        const stepIndex = progressStep.steps.findIndex(s => s.step === stepName);
        if (stepIndex === -1) {
            throw new Error("未找到指定的签到步骤");
        }

        // 更新步骤状态
        progressStep.steps[stepIndex].ischeckIn = false;
        delete progressStep.steps[stepIndex].checkInTime;

        // 更新 progressSteps 并保存
        checkInRecord.set("progressSteps", progressSteps);

        const result = await checkInRecord.save(null, { useMasterKey: true });
        console.log("取消签到成功，数据已更新");
        return ParseHelper.toJSON(result); // 返回更新后的数据
    } catch (error) {
        console.error("更新签到进度时发生错误:", error);
        throw error;
    }
}

function formatDateToStandard(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要+1
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}












module.exports = {
    addCheckIn,
    getCheckInList,
    getCheckInInfoById,
    getCheckInRecord,
    checkIn,
    cancelCheckIn
};